package net.luohuasheng.bee.proxy.core.utils;


import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wudixm
 * @date 2020/8/2 19:04
 */
public class ObjectConventUtils {


    public static <Source, Target> Target copyObject(Source source, Class<Target> targetClass) {
        if (source == null) {
            return null;
        }
        try {
            Target target = targetClass.getConstructor().newInstance();
            BeanUtils.copy(target, source);
            return target;
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            return null;
        }

    }

    public static <Source, Target> List<Target> copyObject(List<Source> sources, Class<Target> targetClass) {
        if (sources == null || sources.isEmpty()) {
            return null;
        } else {
            List<Target> targets = new ArrayList<>();
            for (Source source : sources) {
                try {
                    Target target = targetClass.getConstructor().newInstance();
                    BeanUtils.copy(target, source);
                    targets.add(target);
                } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                    targets.add(null);
                }
            }
            return targets;

        }

    }
}
